package edu.gmu.tec.surveilance.android;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import edu.gmu.tec.R;
import edu.gmu.tec.types.Dossier;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.VideoView;

public class SurveilActivity extends Activity {
	private static final String TAG = "VideoViewDemo";

	private VideoView mVideoView;
	private EditText mPath;
	private Button mPlay;
	private Button mPause;
	private Button mReset;
	private Button mStop;
	private String current;

	private Preview mPreview;
	private Button buttonOk;
	
	private SurveilPlayer surveilPlayer; 
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        
        Dossier dossier = null;
        surveilPlayer = new SurveilPlayer(dossier, this);
        /*
		Intent intent = this.getIntent();
        if (intent.getCategories().contains("edu.tpkl.alert"))
        {
	        
	        
        }
         */
	}
    
    public void setVideoStreaming(){
    	//String stream = intent.getStringExtra("loc");
	       
        //---------------------------------------------------------------------
        //Mong added
        
        // Create our Preview view and set it as the content of our activity.			        
        //    mPreview = new Preview(this);
        //    setContentView(mPreview);
        
        
        setContentView(R.layout.main);	
        
        mPreview = new Preview(this);
        
        buttonOk = (Button) findViewById(R.id.buttonOk);
        
        /*
        ActivitySheetLoader.load(getResources());
        ((FrameLayout) findViewById(R.id.preview)).addView(mPreview);
        */ 		
        buttonOk.setOnClickListener(new OnClickListener() {			
        	public void onClick(View v) {				
        		
        		//new EventHandler().sendOutputEvent("ok");
        		surveilPlayer.ok();
        		toast("Goodbye");
            	finish();
        	}		
        });
        
        
        Log.d(TAG, "onCreate'd");
        
        toast("Please wait. Video loading.");
    }
    public void setNoStream(){
    	setContentView(R.layout.no_stream);
    }

	private void playVideo() {
		try {
			final String path = mPath.getText().toString();
			Log.v(TAG, "path: " + path);
			if (path == null || path.length() == 0) {
				Toast.makeText(this, "File URL/path is empty",
						Toast.LENGTH_LONG).show();

			} else {
				// If the path has not changed, just start the media player
				if (path.equals(current) && mVideoView != null) {
					mVideoView.start();
					mVideoView.requestFocus();
					return;
				}
				current = path;
				mVideoView.setVideoPath(getDataSource(path));
				mVideoView.start();
				mVideoView.requestFocus();

			}
		} catch (Exception e) {
			Log.e(TAG, "error: " + e.getMessage(), e);
			if (mVideoView != null) {
				mVideoView.stopPlayback();
			}
		}
	}

	private String getDataSource(String path) throws IOException {
		if (!URLUtil.isNetworkUrl(path)) {
			return path;
		} else {
			URL url = new URL(path);
			URLConnection cn = url.openConnection();
			cn.connect();
			InputStream stream = cn.getInputStream();
			if (stream == null)
				throw new RuntimeException("stream is null");
			File temp = File.createTempFile("mediaplayertmp", "dat");
			temp.deleteOnExit();
			String tempPath = temp.getAbsolutePath();
			FileOutputStream out = new FileOutputStream(temp);
			byte buf[] = new byte[128];
			do {
				int numread = stream.read(buf);
				if (numread <= 0)
					break;
				out.write(buf, 0, numread);
			} while (true);
			try {
				stream.close();
			} catch (IOException ex) {
				Log.e(TAG, "error: " + ex.getMessage(), ex);
			}
			return tempPath;
		}
	}
	
	public void OKBtn_onClick(View view){
		toast("Goodbye");
    	finish();
    }
    public void call911Btn_onClick(View view){
    	toast("We're sorry, the number you have dialed is out of service.");
    }

	private void toast(String messageText) {
		Toast toast = Toast.makeText(
        		this,
        		messageText,
                Toast.LENGTH_LONG
        );
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
	
	/* Mong added these */
	
	class Preview extends SurfaceView implements SurfaceHolder.Callback {
	    SurfaceHolder mHolder;
	    SocketCamera mCamera;
			    
	    Preview(Context context) {
	        super(context);

	        // Install a SurfaceHolder.Callback so we get notified when the
	        // underlying surface is created and destroyed.
	        mHolder = getHolder();
	        mHolder.addCallback(this);
	        //mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	        mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);

	    }
    
	    public void done (){
			mCamera.stopPreview(); 
	        mCamera.release(); 
	        mCamera = null; 
		}
	    public void surfaceCreated(SurfaceHolder holder) {
	        // The Surface has been created, acquire the camera and tell it where
	        // to draw.
	        mCamera = SocketCamera.open();
	        try {
	           mCamera.setPreviewDisplay(holder);
	        } catch (IOException exception) {
	            mCamera.release();
	            mCamera = null;
	            // TODO: add more exception handling logic here
	        }
	    }

	    public void surfaceDestroyed(SurfaceHolder holder) {
	        // Surface will be destroyed when we return, so stop the preview.
	        // Because the CameraDevice object is not a shared resource, it's very
	        // important to release it when the activity is paused.
	    	if (mCamera != null) {
	    		mCamera.stopPreview();
	    		mCamera.release();
	    		mCamera = null;
	    	}
	    }

	    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
	        // Now that the size is known, set up the camera parameters and begin
	        // the preview.
	        Parameters parameters = mCamera.getParameters();
//	        parameters.setPreviewSize(w, h);
	        mCamera.setParameters(parameters);
	        mCamera.startPreview();
	    }
	    
	}
}